package com.sloan.community.util;

import lombok.extern.slf4j.Slf4j;
import org.jcodec.api.FrameGrab;
import org.jcodec.api.JCodecException;
import org.jcodec.common.io.FileChannelWrapper;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.model.Picture;
import org.jcodec.scale.AWTUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.channels.Channels;

/**
 * 视频操作工具类
 */
@Slf4j
public class VideoUtils {

        /*** 图片格式*/
        private static final String FILE_EXT = "jpg";

        /*** 帧数*/
        private static final int THUMB_FRAME = 5;

        /**
         * 获取指定视频的帧并保存为图片至指定目录
         *
         * @param videoFilePath 源视频文件路径
         * @param frameFilePath 截取帧的图片存放路径
         */
        public static void fetchFrame(String videoFilePath, String frameFilePath) throws Exception {
            File videoFile = new File(videoFilePath);
            File frameFile = new File(frameFilePath);
            getThumbnail(videoFile, frameFile);
        }


        /**
         * 获取第一帧缩略图
         *
         * @param videoFile  视频路径
         * @param targetFile 缩略图目标路径
         */
        public static void getThumbnail(File videoFile, File targetFile) {
            try {
                // 根据扩展名创建一个新文件路径
                Picture picture = FrameGrab.getFrameFromFile(videoFile, THUMB_FRAME);
                BufferedImage bufferedImage = AWTUtil.toBufferedImage(picture);
                ImageIO.write(bufferedImage, FILE_EXT, targetFile);
            } catch (IOException | JCodecException e) {
                e.printStackTrace();
                log.error("获取第一帧缩略图异常：", e);
            }
        }

        public static void getFirstFrame(FileInputStream inputStream,Integer frame, String targetFile) throws Exception {
            FileChannelWrapper channelWrapper = new FileChannelWrapper((inputStream).getChannel());
            Picture picture = FrameGrab.createFrameGrab(channelWrapper)
                    .seekToFramePrecise(frame)
                    .getNativeFrame();
            BufferedImage bufferedImage = AWTUtil.toBufferedImage(picture);
            ImageIO.write(bufferedImage, FILE_EXT, new File(targetFile));
        }

        public static void main(String[] args) {
            try {
                // C:\Users\19252\AppData\Local\Temp\temp15623010144997611211.mp4
                long startTime = System.currentTimeMillis();
//                getThumbnail(new File("C:\\Users\\19252\\Desktop\\aaa.mp4"), new File("C:\\Users\\19252\\Desktop\\123123213.jpg"));
                getFirstFrame(new FileInputStream(new File("C:\\Users\\19252\\Desktop\\aaa.mp4")),Integer.MAX_VALUE,"C:\\Users\\19252\\Desktop\\123123213.png");
                System.out.println("截取图片耗时：" + (System.currentTimeMillis() - startTime));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

}
